package com.nakamachizu.controller.mixi;

import java.util.Calendar;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.TimeZoneLocator;

import com.google.appengine.api.datastore.KeyFactory;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ErrorsUtil;

public class MakeController extends Controller {

    private static final Logger log = Logger.getLogger(MakeController.class.getName());
    private String mixiSessionKey = "";
    
    @Override
    public Navigation run() throws Exception {
        if(validate()){
            MapDataService service = new MapDataService();
            mixiSessionKey = requestScope("sid");
            MixiSessionData session = service.getMixiSessionData(mixiSessionKey);
            
//            RestfulService rfs = new RestfulService();
//            rfs.makeSignature(
//                session.getViewerId(),
//                RestfulService.TARGET_UID_ME,
//                RestfulService.TARGET_TYPE_FRIENDS,
//                RestfulService.FORMAT_JSON,
//                RestfulService.DEFAULT_COUNT,
//                RestfulService.DEFAULT_START_INDEX);
//            if(rfs.request() == 200){
//                log.info(rfs.getHttpHeaderString());
//                log.info(rfs.getContents());
//                PersonFriendsModel model = JSON.decode(rfs.getContents(), PersonFriendsModel.class);
//                log.info("total:" + Integer.toString(model.getTotalResults()));
//                log.info("entry0:" + model.getEntry()[0].get(PersonFriendsModel.DISPLAY_NAME));
//                log.info("entry1:" + model.getEntry()[1].get(PersonFriendsModel.DISPLAY_NAME));
//            }else{
//                log.info(rfs.getHttpHeaderString());
//                log.info(rfs.getContents());
//            }
            
            if(session.isOwner()){
                
                MapData old = service.getMapData(session.getAdminMailAddress());
                if(old != null){
                    service.deleteMapData(old);
                }
                
                MapData map = new MapData();
                map.setAdminMailAddress(session.getAdminMailAddress());
                map.setExpire(service.getExpire(AppConstant.DEFAULT_EXPIRE_DAYS()));
                map.setFromMailAddress(AppConstant.FROM_MAIL_ADDRESS_SYSTEM());
                map.setLineType(AppConstant.LINE_TYPE_LINE());
                map.setAccessLevel(AppConstant.ACCESSLEVEL_FRIENDS());
                map.setAccessKey(service.makeAccessKey());
                
                Datastore.put(map);
                
                session.setMapKey(map.getAccessKey());
                session.setEntryDate(Calendar.getInstance(TimeZoneLocator.get()).getTime());
                Datastore.put(session);
                
                return redirect("/mixi/view?sid=" + mixiSessionKey);
            }
        }
        
        return forward("/jsp/pc/mixi/error.jsp");
    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("sid", v.required());
        result = v.validate();
        
        return result;
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/jsp/pc/mixi/error.jsp");
    }
}
